<template>
  <div class="container app-container">
    <div class="form">
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <div
          class="title"
          style="
            margin: 20px 0 20px 0;
            height: 20px;
            line-height: 20px;
            border-left: 1px solid #ccc;
            text-indent: 15px;
          "
        >
          基本信息
        </div>
        <el-row>
          <el-col :span="8">
            <el-form-item label="归属企业" prop="companyId">
              <el-select v-model="form.companyId" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in companyList"
                  :key="item.id"
                  :label="item.companyNickName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="项目类型" prop="projectType">
              <el-select v-model="form.projectType" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in projectTypeList"
                  :key="item.code"
                  :label="item.info"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="起止时间" prop="createTime">
              <el-date-picker
                v-model="form.createTime"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="至"
                start-placeholder="起始日期"
                end-placeholder="截止日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item
              label="项目地址"
              prop="addressInfo"
              :rules="[
                {
                  type: 'object',
                  required: true,
                  fields: {
                    province: { type: 'string', required: true, message: '省必填' },
                    city: { type: 'string', required: true, message: '市必填' },
                    //district: { type: 'string', required: true, message: '区必填' },
                    address: { type: 'string', required: true, message: '详细地址必填' },
                    longitude: { required: true, message: '经度必填，可点击搜索地图确定经纬度' },
                    latitude: { required: true, message: '维度必填，可点击搜索地图确定经纬度' },
                  },
                },
              ]"
            >
              <baidu-map-form @input="handleUpdateAddress" :value="form.addressInfo"></baidu-map-form>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="footer">
      <el-button type="primary" class="submit-btn" @click="submitForm">
        {{ isEdit ? '确定保存' : '确定新增' }}
      </el-button>
    </div>
  </div>
</template>

<script>
import { getCompanyList } from '@/api/common';
import { addProject, getProjectDetail, updateProject } from '@/api/project';
import baiduMapForm from '../baidu-map-form/index.vue';

export default {
  name: 'SaveProject',
  components: {
    baiduMapForm,
  },
  data() {
    return {
      // 标题
      title: '',
      // 初始化 id 为 null
      id: null,
      // 初始化 isEdit 为 false
      isEdit: false,
      // 表单参数
      form: {
        id: null, // id
        companyId: null, // 所属企业id
        projectName: '', // 项目名称
        projectType: null, // 项目类型
        createTime: null,
        addressInfo: {
          province: '', // 省
          city: '', //市
          district: '', // 区
          address: '', // 地址
          longitude: '', // 经度
          latitude: '', // 纬度
        }
      },
      // 企业列表
      companyList: [],
      //项目类型列表
      projectTypeList: [
        {
          code: '1',
          info: '挖沙',
        },
        {
          code: '2',
          info: '清淤',
        },
        {
          code: '3',
          info: '施工',
        },
        {
          code: '4',
          info: '运输',
        },
      ],
      // 表单校验
      rules: {
        companyId: [{ required: true, message: '归属企业不能为空', trigger: 'blur' }],
        projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
        projectType: [{ required: true, message: '项目类型不能为空', trigger: 'blur' }],
        // address: [{ required: true, message: '项目地址不能为空', trigger: 'blur' }],
        // longitude: [{ required: true, message: '请在地图选择定位', trigger: 'blur' }],
        // latitude: [{ required: true, message: '请在地图选择定位', trigger: 'blur' }],
        // province: [{ required: true, message: '省份不能为空', trigger: 'blur' }],
        // city: [{ required: true, message: '市不能为空', trigger: 'blur' }],
        // district: [{ required: true, message: '区不能为空', trigger: 'blur' }],
        createTime: [{ required: true, message: '项目日期不能为空', trigger: 'blur' }],
      },
    };
  },
  created() {
    // 通过 $route.params 获取路由参数
    this.id = this.$route.query.id ? this.$route.query.id : null;
    this.form.companyId = this.$route.query.companyId ? Number(this.$route.query.companyId) : null;
    // 判断是否存在 id 参数
    this.isEdit = !!this.id;
    if (this.isEdit) {
      // 如果存在 id 参数，则说明当前页面是修改状态
      // 可以根据 id 参数获取需要修改的数据
      this.getDataById(this.id);
    } else {
      // 如果不存在 id 参数，则说明当前页面是新增状态
    }
  },
  mounted() {
    this.getCompanyList();
  },
  methods: {
    // 获取企业
    getCompanyList() {
      getCompanyList().then((res) => {
        this.companyList = res.data;
      });
    },
    /** 获取form表单数据 */
    async getDataById(id) {
      getProjectDetail(id).then((res) => {
        const {
          province,
          city,
          district,
          longitude,
          latitude,
          projectAddress,
          startDate,
          endDate,
          companyId,
          projectName,
          projectType,
          remark
        } = res.data;
        this.form = {
          companyId,
          projectName,
          projectType,
          remark,
          createTime: [startDate, endDate],
          addressInfo: {
            longitude: longitude + '',
            latitude: latitude + '',
            address: projectAddress,
            province: province,
            city: city,
            district: district,
          }
        }
      });
    },
    handleUpdateAddress(value) {
      this.form.addressInfo = value;
      // this.$refs.form.validateField('addressInfo');
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.id != null) {
            this.$confirm('确定修改当前内容', '确定保存', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(() => {
                // 调用修改接口
                this.handleUpdate();
              })
              .catch(() => {});
          } else {
            this.$confirm('确定新增', '确定新增', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(() => {
                // 调用新增接口
                this.handleAdd();
              })
              .catch(() => {});
          }
        }
      });
    },

    /** 新增 */
    handleAdd() {
      let saveData = {
        ...this.form,
      };
      this.$modal.loading('正在保存...');

      saveData.startDate = saveData.createTime[0];
      saveData.endDate = saveData.createTime[1];
      saveData.address = saveData.addressInfo.address;
      saveData.city = saveData.addressInfo.city;
      saveData.latitude = saveData.addressInfo.latitude;
      saveData.longitude = saveData.addressInfo.longitude;
      saveData.district = saveData.addressInfo.district;
      saveData.province = saveData.addressInfo.province;

      addProject(saveData)
        .then((res) => {
          if (res.code === 200) {
            this.close();
          } else {
            this.$message.error(res.message);
          }
          this.$modal.closeLoading();
        })
        .catch((err) => {
          this.$modal.closeLoading();
        });
    },

    /** 更新 */
    handleUpdate() {
      let saveData = {
        ...this.form,
      };
      saveData.id = this.id;
      this.$modal.loading('正在保存...');

      saveData.startDate = saveData.createTime[0];
      saveData.endDate = saveData.createTime[1];
      saveData.address = saveData.addressInfo.address;
      saveData.city = saveData.addressInfo.city;
      saveData.latitude = saveData.addressInfo.latitude;
      saveData.longitude = saveData.addressInfo.longitude;
      saveData.district = saveData.addressInfo.district;
      saveData.province = saveData.addressInfo.province;

      updateProject(saveData)
        .then((res) => {
          if (res.code == 200) {
            this.close();
          }
          this.$modal.closeLoading();
        })
        .catch((err) => {
          this.$modal.closeLoading();
        });
    },

    /** 关闭按钮 */
    close() {
      // 跳转地址 和 携带参数
      const obj = {
        path: '/platform/project/list/index',
      };
      this.$tab.closeOpenPage(obj).then(() => {
        this.$tab.refreshPage(obj);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  position: relative;
}

.submit-btn {
  position: fixed;
  bottom: 10px;
  left: 50%;
}
</style>
